package com.fang.transfer.file.client.thread;

import com.fang.transfer.file.client.AppContext;
import com.fang.transfer.file.common.code.ClientSendCode;
import com.fang.transfer.file.common.model.TransferFileRequest;

import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.BitSet;

/**
 * 检测文件完整(接收方)
 */
public class FileCheckThread implements Runnable {


    private final TransferFileRequest request;

    public FileCheckThread(TransferFileRequest request) {
        this.request = request;
        this.request.setStatus(5);
    }

    @Override
    public void run() {
        try {
            Thread.currentThread().setName("FileCheckThread");
            doRun();
        } catch (InterruptedException interruptedException) {
            request.notifyAll();
            System.out.println("进入下一轮传输");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void doRun() throws Exception {
        System.out.println("检查文件完整 do Run");
        BitSet curData = request.getCurData();
        if (curData == null) {
            request.initParam();
            curData = request.getCurData();
        }
        ArrayList<Integer> indexList = new ArrayList<>();
        for (int i = 0; i < request.getMaxPackage(); i++) {
            boolean b = curData.get(i);
            if (!b) {
                indexList.add(i);
                if (indexList.size() > 300) {
                    break;
                }
            }
        }
        request.setReSendIndex(indexList);
        if (!indexList.isEmpty()) {
            request.setStatus(4);
            System.out.println("重新传输:" + request.getReSendIndex().size());
            AppContext.tcpUtil.writeAndFlush(ClientSendCode.RE_SEND_FILE_DATA_INDEX, request);
            return;
        }
        System.out.println("传输完成");
        RandomAccessFile file = AppContext.randomAccessFileMap.get(request.getId());

        if (file != null) {
            System.out.println("关闭文件流");
            file.close();
        }
        AppContext.tcpUtil.writeAndFlush(ClientSendCode.SEND_FILE_FINISH, request);
        return;

    }


}
